const express = require('express');
const fs = require('fs');
const path = require('path');
const houTai = express.Router();
const multer = require('multer');
const md5 = require('md5');

//解析json
houTai.use(express.json());
//解析表单urlencoded
houTai.use(express.urlencoded({	extended: true }));
//后台静态文件
houTai.use(express.static(path.resolve(`viteVue/dist`)));

//调用jieKou
function jieKou(muLu) {
	let wenJianLieBiao = fs.readdirSync(path.resolve(muLu));
	wenJianLieBiao.forEach(x => {
		let luJing = `${muLu}/${x}`
		if (fs.statSync(path.resolve(muLu, x)).isFile()) {
			let a;
			//清除require缓存
			delete require.cache[require.resolve(path.resolve(luJing))];
			a = require(path.resolve(luJing));
			//清除路由
			houTai.stack.forEach((luYou, jian, luYouShuZu) => {
				if (x.replace('.js', '') == luYou.name) {
					luYouShuZu.splice(jian, 1);
				};
			})
			houTai.use('/jieKou', a);
		}else jieKou(luJing);
	})
}
jieKou('jieKou');

//监听jieKou文件
//linux不支持watch recursive

// fs.watch(path.resolve('jieKou'), { recursive: true }, (leiXing, wenJianMing) => {
// 	jieKou('jieKou');
// 	  if (wenJianMing) {
// 	    console.log(`支持文件名: ${wenJianMing}`);
// 	  } else {
// 	    console.log('不支持文件名');
// 	  }
// });

//设置上传目录、文件名
let storage = multer.diskStorage({
	destination: function(qingQiu, wenJian, cb) {
		cb(null, path.resolve('jingTai/shangChuan'))
	},
	filename: function(qingQiu, wenJian, cb) {
		const qianZhuiMing = Date.now();
		cb(null, qianZhuiMing + wenJian.originalname)
	}
})
let shangChuan = multer({ storage: storage });

//上传图片
houTai.post('/shangChuan', shangChuan.single('wenJian'), async function(qingQiu, xiangYing) {
	let wenJianLuJing = qingQiu.file.path.match(/shangChuan.*$/g)[0].replace('\\','/');
	let shuJu = { url: '/' + wenJianLuJing };
	xiangYing.append('content-type', 'application/json')
	xiangYing.send(JSON.stringify(shuJu));
})

module.exports = houTai;
